import hashlib
import os

from django.shortcuts import render, redirect

from app01.models import Employee, Departement
from app01.utils.pagination import Pagination


def employee_delete(request,uid):
    Employee.objects.filter(id=uid).delete()
    return redirect('/emp/list/')


def employee_list(request):
    # querySet = Employee.objects.all()
    data_dict = {} # 用于接收模糊查询的参数
    q_name = request.GET.get('q_name')
    """
        如果要模糊查询某个字段，需要再字段后面加 __contains
        data_dict['e_name__contains'] = q_name  是模式查询
        data_dict['e_name'] = q_name  是精确查询
    """
    if q_name:
        data_dict['e_name__contains'] = q_name

    querySet = Employee.objects.filter(**data_dict)
    # 实例化分页对象
    page_object = Pagination(request,querySet)
    context = {
        "queryset": page_object.page_queryset,   # 循环使用的对象
        "page_string": page_object.html() # 分页使用的对象
    }
    return render(request, 'employee_list.html', context)

def employee_add(request):
    if request.method == 'GET':
        # 查询部门信息，在页面中显示
        depts = Departement.objects.all()
        return render(request, 'employee_add.html',{'depts':depts})
    # Post请求的话需要获取前段页面发送过来的数据
    ename = request.POST.get('e_name')
    password = md5_password(request.POST.get('password')) # 加密后的密码
    gender = request.POST.get('gender')
    age = request.POST.get('age')
    create_time = request.POST.get('create_time')
    salary = request.POST.get('account')
    dept_id = request.POST.get('dept')
    # 根据部门id获取到部门对象
    depart = Departement.objects.filter(id=dept_id).first()
    Employee.objects.create(
        e_name=ename,
        password=password,
        gender=gender,age=age,
        create_time=create_time,
        account=salary,
        depart=depart,
    )
    return redirect('/emp/list/')



# 密码加密的方法
def md5_password(password):
    # 生成一个32位的随机盐值
    salt = os.urandom(32).hex()
    str_password = salt + password + salt
    new_password = hashlib.md5(str_password.encode('utf-8')).hexdigest()
    return new_password

def employee_update(request,uid):
    if request.method == 'GET':
        # 根据id查询数据并进行回显
        emp = Employee.objects.filter(id=uid).first()
        depts = Departement.objects.all()
        return render(request, 'employee_update.html',{'emp':emp,'depts':depts})
    ename = request.POST.get('e_name')
  # 加密后的密码
    gender = request.POST.get('gender')
    age = request.POST.get('age')
    create_time = request.POST.get('create_time')
    salary = request.POST.get('account')
    dept_id = request.POST.get('dept')
    # 根据部门id获取到部门对象
    depart = Departement.objects.filter(id=dept_id).first()
    Employee.objects.filter(id=uid).update(
        e_name=ename,
        gender=gender,
        age=age,
        create_time=create_time,
        account=salary,
        depart=depart,
    )
    return redirect('/emp/list/')